package com.example.servlet;

import com.example.dao.SalaryDao;
import com.example.entity.Salary;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * 工资管理Servlet，处理工资相关请求
 */
@WebServlet("/salary")
public class SalaryServlet extends HttpServlet {
    private static final Logger LOGGER = Logger.getLogger(SalaryServlet.class.getName());
    private SalaryDao salaryDao = new SalaryDao();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String action = req.getParameter("action");

        if (action == null) {
            action = "list";
        }

        try {
            switch (action) {
                case "list":
                    listSalaries(req, resp);
                    break;
                case "add":
                    req.getRequestDispatcher("addSalary.jsp").forward(req, resp);
                    break;
                case "edit":
                    getSalary(req, resp);
                    break;
                case "delete":
                    deleteSalary(req, resp);
                    break;
                case "pay":
                    paySalary(req, resp);
                    break;
                default:
                    listSalaries(req, resp);
            }
        } catch (Exception e) {
            LOGGER.log(Level.SEVERE, "Error handling salary request", e);
            req.setAttribute("errorMessage", "操作失败: " + e.getMessage());
            req.getRequestDispatcher("/error.jsp").forward(req, resp);
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String action = req.getParameter("action");

        try {
            switch (action) {
                case "add":
                    addSalary(req, resp);
                    break;
                case "update":
                    updateSalary(req, resp);
                    break;
            }
        } catch (Exception e) {
            LOGGER.log(Level.SEVERE, "Error handling salary request", e);
            req.setAttribute("errorMessage", "操作失败: " + e.getMessage());
            req.getRequestDispatcher("/error.jsp").forward(req, resp);
        }
    }

    private void listSalaries(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        List<Salary> salaries = salaryDao.getAllSalaries();
        if (salaries.isEmpty()) {
            LOGGER.warning("Warning: Salary list is empty");
        }
        req.setAttribute("salaries", salaries);
        req.getRequestDispatcher("salaryList.jsp").forward(req, resp);
    }

    private void addSalary(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {
        int employeeId = 0;
        double baseSalary = 0;
        double bonus = 0;
        double deduction = 0;
        try {
            employeeId = Integer.parseInt(req.getParameter("employee_id"));
            baseSalary = Double.parseDouble(req.getParameter("base_salary"));
            bonus = Double.parseDouble(req.getParameter("bonus"));
            deduction = Double.parseDouble(req.getParameter("deduction"));
        } catch (NumberFormatException e) {
            LOGGER.log(Level.SEVERE, "Invalid input for employeeId, baseSalary, bonus or deduction", e);
            req.setAttribute("errorMessage", "员工 ID、基本工资、奖金或扣除项输入无效");
            req.getRequestDispatcher("addSalary.jsp").forward(req, resp);
            return;
        }
        String month = req.getParameter("month");
        String status = "unpaid";

        Salary salary = new Salary();
        salary.setEmployeeId(employeeId);
        salary.setMonth(month);
        salary.setBaseSalary(baseSalary);
        salary.setBonus(bonus);
        salary.setDeduction(deduction);
        salary.setStatus(status);

        salaryDao.addSalary(salary);

        resp.sendRedirect("salary?action=list");
    }

    private void getSalary(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        int salaryId = 0;
        try {
            salaryId = Integer.parseInt(req.getParameter("id"));
        } catch (NumberFormatException e) {
            LOGGER.log(Level.SEVERE, "Invalid input for salaryId", e);
            req.setAttribute("errorMessage", "工资记录 ID 输入无效");
            req.getRequestDispatcher("/error.jsp").forward(req, resp);
            return;
        }
        Salary salary = salaryDao.getSalaryById(salaryId);
        req.setAttribute("salary", salary);
        req.getRequestDispatcher("editSalary.jsp").forward(req, resp);
    }

    private void deleteSalary(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        int salaryId = 0;
        try {
            salaryId = Integer.parseInt(req.getParameter("id"));
        } catch (NumberFormatException e) {
            LOGGER.log(Level.SEVERE, "Invalid input for salaryId", e);
            req.setAttribute("errorMessage", "工资记录 ID 输入无效");
            try {
                req.getRequestDispatcher("/error.jsp").forward(req, resp);
            } catch (ServletException ex) {
                throw new RuntimeException(ex);
            }
            return;
        }
        salaryDao.deleteSalary(salaryId);
        resp.sendRedirect("salary?action=list");
    }

    private void paySalary(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        int salaryId = 0;
        try {
            salaryId = Integer.parseInt(req.getParameter("id"));
        } catch (NumberFormatException e) {
            LOGGER.log(Level.SEVERE, "Invalid input for salaryId", e);
            req.setAttribute("errorMessage", "工资记录 ID 输入无效");
            try {
                req.getRequestDispatcher("/error.jsp").forward(req, resp);
            } catch (ServletException ex) {
                throw new RuntimeException(ex);
            }
            return;
        }
        salaryDao.paySalary(salaryId);
        resp.sendRedirect("salary?action=list");
    }

    private void updateSalary(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {
        int id = 0;
        int employeeId = 0;
        double baseSalary = 0;
        double bonus = 0;
        double deduction = 0;
        try {
            id = Integer.parseInt(req.getParameter("id"));
            employeeId = Integer.parseInt(req.getParameter("employee_id"));
            baseSalary = Double.parseDouble(req.getParameter("base_salary"));
            bonus = Double.parseDouble(req.getParameter("bonus"));
            deduction = Double.parseDouble(req.getParameter("deduction"));
        } catch (NumberFormatException e) {
            LOGGER.log(Level.SEVERE, "Invalid input for id, employeeId, baseSalary, bonus or deduction", e);
            req.setAttribute("errorMessage", "ID、员工 ID、基本工资、奖金或扣除项输入无效");
            req.getRequestDispatcher("/error.jsp").forward(req, resp);
            return;
        }
        String month = req.getParameter("month");
        String status = req.getParameter("status");

        Salary salary = new Salary();
        salary.setId(id);
        salary.setEmployeeId(employeeId);
        salary.setMonth(month);
        salary.setBaseSalary(baseSalary);
        salary.setBonus(bonus);
        salary.setDeduction(deduction);
        salary.setStatus(status);

        salaryDao.updateSalary(salary);

        resp.sendRedirect("salary?action=list");
    }
}